import * as api from "@/servers/users"
import { Effect } from "umi"
export interface Istate {
    productList: any[],
    userInfo: any
}
interface IProductList {
    type: 'setProductList',
    payload: any[]
}
interface ILogin {
    type: 'setUserInfo',
    payload: any
}
export default {
    namespace: 'users', //命名空间
    state: {
        productList: [],
        userInfo: {}
    },
    reducers: { //相当于mutation,用来修改state数据
        // 第一个参数是state,第二个参数是action,可以直接解构出payload
        setProductList(state: Istate, { payload }: IProductList) {
            // 威少写法
            // state.productList = payload.data
            // 文档写法
            return {
                ...state,
                productList: payload
            }
        },
        setUserInfo(state: Istate, { payload }: ILogin) {
            return {
                ...state,
                userInfo: payload
            }
        }
    },
    effects: { //副作用,相当于vuex中的actions 处理异步逻辑
        *getProductList({ payload }: IProductList, { call, put }: any): any {
            try {
                let res = yield call(api.getProductListApi) //第二个参数是payload,如果你的请求需要传参的话
                yield put({
                    type: 'setProductList',
                    payload: res.data
                })
            } catch (e) {
                console.log(e)
            }
        },
        *login({ payload }: ILogin, { call, put }: any): any {
            try {
                let res = yield call(api.loginApi, payload, payload) //第二个参数是payload,如果你的请求需要传参的话
                yield put({
                    type: 'setUserInfo',
                    payload: res.userInfo
                })
            } catch (e) {
                console.log(e)
            }
        },
    }
}